<template>
  <div class="comment-list">
    <van-cell :title="replay ? '' : '全部评论' "></van-cell>
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="已展示所有评论"
      @load="onLoad"
    >
      <comment-item
      v-for="(comment, index) in list"
      :key="index"
      :comment="comment"
      @reply-click="$emit('reply-click', $event)"></comment-item>
      <!-- <van-cell v-for="(comment, index) in list"
      :key="index"
      :title="comment.content" /> -->
    </van-list>
  </div>
</template>

<script>
import { getComments } from '@/api/comment'
import commentItem from './comment-item'

export default {
  name: 'CommentList',
  components: {
    commentItem
  },
  props: {
    replay: {
      type: Boolean,
      default: false
    },
    // 如果获取文章评论 则传递文章ID
    // 如果获取评论回复 则传递评论id
    source: {
      type: [Number, String, Object],
      required: true
    },
    // 获取文章评论 a
    // 获取评论回复 c
    type: {
      type: String,
      default: 'a'
    },
    list: {
      type: Array,
      default: () => []
      // default: function () {
      //   return []
      // }
    }
  },
  data () {
    return {
      // list: [],
      loading: false,
      finished: false,
      offset: null,
      limit: 10
    }
  },
  methods: {
    async onLoad () {
      // 1. 请求获取数据
      const { data } = await getComments({
        type: this.type,
        source: this.source.toString(),
        offset: this.offset,
        limit: this.limit
      })
      this.$emit('update-total-count', data.data.total_count)
      // 2. 把数据放到列表中
      const { results } = data.data
      this.list.push(...results)
      // 3. 将本次的loading关闭 加载状态结束
      this.loading = false
      // 4. 判断是否有数据
      //  如果有 获取下一页数据
      // 如果没有 将finished设置为true
      if (results.length) {
        this.offset = data.data.last_id
      } else {
        this.finished = true
      }
    }
  }
}
</script>

<style lang="less" scoped>

</style>
